import { yellow, red, green, blue, lightBlue, cyan, magenta, lightRed, stripColors } from 'kolorist';
import { writeFile } from 'node:fs/promises';
import { join } from 'node:path'
import { SyncHook } from 'tapable'
import { mkdirSync } from 'node:fs'
type Hooks = {
  onRuntimeFiles: SyncHook<any>,
  onLog: SyncHook<any>,
}

type Api = {

}

type Plugin = {
  name: string,
  onRuntimeFiles?: () => void,
  onLog?: (name) => void,
}

class QPSPlugin {
  hooks: Hooks
  hasHooks: Array<string>
  constructor() {
    this.hasHooks = []
    this.hooks = {
      onRuntimeFiles: new SyncHook(),
      onLog: new SyncHook(['message']),

    }
  }
  register(props: Plugin) {
    const { name, onRuntimeFiles, onLog } = props;

    if (!this.hasHooks.includes(name)) {

      if (onRuntimeFiles) {
        this.hooks.onRuntimeFiles.tap(name, () => {
          const info = onRuntimeFiles();
          const path = process.cwd() + `/.qps/${info.name}`;
          mkdirSync(path, { recursive: true });
          writeFile(join(path, `./${info.fileName}`), info.content);
          
        })
      }

      if (onLog) {
        this.hooks.onLog.tap(name, onLog)
      }

      this.hasHooks.push(name)
    }

  }
  onRuntimeFiles() {
    this.hooks.onRuntimeFiles.call();
  }
  onLog() {
    this.hooks.onLog.call('log')
  }
}


const api = new QPSPlugin();


api.register({
  name: 'name',
  onLog: (name) => {
    console.log("name33", name)
  },
  onRuntimeFiles: () => {

    return {
      name: 'plugin-model',
      fileName: 'name3232.js',
      content: 'export const add=(a,b)=>{ return a+b }'
    }
  }
})
api.onRuntimeFiles()
api.onLog()